package com.csxy.yhj.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.csxy.yhj.service.OssService;
import com.csxy.yhj.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class OssServiceImpl implements OssService {
    private String url;

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        //TODD 上传头像

        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //输入流
        InputStream inputStream = null;
        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件输入流
            inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //在文件名称添加唯一的uuid
            String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            //把文件按时间分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            //上传文件
            ossClient.putObject(bucketName, fileName, inputStream);
            //关闭OSSClient
            ossClient.shutdown();
            //上传之后文件路径
             url = "https://" + bucketName + "." + endpoint + "/" + fileName;

        }catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
}
